<template>
  <view class="profile">
    <!-- 头部信息 -->
    <view class="header">
      <u-avatar class="avatar"  size="150rpx"  @click="previewImage()" :src="userAvatar" mode="aspectFill" />
      <view class="info">
        <text class="nickname">{{username}}</text>
		 <text class="follow-icon" v-if="unAllowFollow==false" @click="changeFollow()">
			 <view class="notFollow" v-if="isFollow==false">
			 	关注
			 </view>
			 <view class="followed" v-else>
			 	已关注
			 </view>
		 </text>
        <text class="chat-icon" v-if="unAllowChat==false" @click="goToChat(uid,username)">去私信</text> <!-- 新增的去聊天文字图标 -->
        <view class="follow-info">
          <text class="follow">粉丝 {{funs}} 人</text>
          <text class="follow">关注 {{follow}} 人</text>
        </view>
      </view>
    </view>
    <!-- 成就展示 -->
<!--    <view class="achievements">
      <view class="level-info">
        <text class="level">财力等级 3</text>
        <text class="level">总分 2380</text>
        <text class="level">当月 100</text>
      </view>
    </view> -->
    <!-- 标签 -->
    <view class="tags" >
		<view class="noTags" v-if="tags.length==0">
			该用户还没有感兴趣的领域
		</view>
      <view v-for="(tag, index) in tags" :key="index" class="tag">{{ tag }}</view>
    </view>
    <!-- 博客列表（滑动区域） -->
    <scroll-view class="blog-list" scroll-y="true">
		<view class="noTags" v-if="blogs.length==0">
			该用户还没有发布任何博客
		</view>
      <view v-for="(blog, index) in blogs" :key="index" class="blog-item" @click="gotoPost(blog.postId)">
        <text class="blog-title">{{ blog.title }}</text>
        <text class="blog-date">{{ blog.date }}</text>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import method from '@/utils/methods.js'
import {pathToBase64,base64ToPath} from 'image-tools'
export default {
  data() {
    return {
      uid: 0,
	  myUid:0,
	  token:null,
	  userAvatar:"",
	  username:"-",
	  unAllowChat:false,
	  isFollow:false,
	  unAllowFollow:false,
	  currentPage:0,
	  funs:"-",
	  follow:"-",
	  pageSize:20,
      tags: [],
      blogs: [
        // { title: "Java如何用JDBC操作数据库", date: "2023.06.14" },
      ],
    };
  },
  onLoad(param) {
    this.uid = 	Number(param.uid);
	this.unAllowChat=param.unAllowChat||false;
	console.log("unAllowChat="+this.unAllowChat)
	console.log("uid="+this.uid)
	this.username=param.username
	this.myUid=uni.getStorageSync('UID')||null
	this.token=uni.getStorageSync('token')||null
	this.getUserAvatar(this.uid)
	if(this.token==null||this.myUid==null){
		uni.navigateBack()
		uni.navigateTo({
			url:"/pages/login/login"
		})
		return
	}
	if(this.myUid==this.uid){
		this.unAllowChat=true;
		this.unAllowFollow=true;
	}else{
		method.isFollow(this.myUid,this.uid,this.myUid,this.token).then((result)=>{
			this.isFollow=result.follow
		}).catch((error)=>{
			console.log(error.message)
		})
	}
	this.getTags()
	 this.getPosts()
	 this.getUserStat()
  },
  onShow() {
    uni.setNavigationBarTitle({
      title: "个人详情"
    });
  },
  methods: {
	  formatNumber(num) {
	      if (num >= 100000000) { // 大于等于1亿
	          return (num / 100000000).toFixed(1) + '亿'; // 转换为亿
	      } else if (num >= 10000) { // 大于等于1万
	          return (num / 10000).toFixed(1) + 'w'; // 转换为万
	      }
	      return num.toString(); // 小于1万的数字直接返回
	  },
	  getTags(){
		uni.request({
			url:this.baseUrl+"/getUserInterest",
			method:"POST",
			header:{
				token:this.token,
				uid:this.myUid
			},
			data:{
				data:{
					userId:Number(this.uid)
				},
				msgType:"getUserInterest"
			},
			success: (res) => {
				if(res.data.code==1){
					res.data.data.forEach((data)=>{
						this.tags.push(data.tagName)
					})
				}
			}
		})
	  },
	  getPosts(){
		uni.request({
			url:this.baseUrl+"/getUserPosts",
			method:"POST",
			header:{
				token:this.token,
				uid:this.myUid
			},
			data:{
				data:{
					userId:Number(this.uid),
					currentPage:this.currentPage,
					pageSize:this.pageSize
				},
				msgType:"getUserPosts"
			},
			success: (res) => {
				console.log("收到博客：",res.data)
				this.currentPage+=this.pageSize
				if(res.data.code==1){
					console.log(res.data)
					res.data.data.forEach((data)=>{
						this.blogs.push({
							title:data.title,
							postId:data.postId,
							date:data.createdAt.split("T")[0]
						})
					})
				}
			}
		})
	  },
	  getUserStat(){
		  uni.request({
		  	url:this.baseUrl+"/getOtherUserData",
		  	method:"POST",
		  	header:{
		  		token:this.token,
		  		uid:this.myUid
		  	},
		  	data:{
		  		data:{
		  			userId:Number(this.uid),
		  		},
		  		msgType:"getOtherUserData"
		  	},
		  	success: (res) => {
		  		this.currentPage+=this.pageSize
		  		if(res.data.code==1){
					console.log(res.data)
					this.funs=this.formatNumber(res.data.data.followersCount)
					this.follow=this.formatNumber(res.data.data.followingCount)
		  		}
		  	}
		  })
	  },
	  previewImage() {
	    let that = this;
	    			uni.showLoading({
	    				title: "加载中..."
	    			})
	    			base64ToPath(this.userAvatar) 
	    				.then(path => {
	    					let imgs = [];
	    					uni.hideLoading()
	    					imgs[0] = path;
	              
	    					uni.previewImage({
	    						current: 0,
	    						urls: imgs,
	  						longPressActions: {
	  							itemList: ['发送给朋友', '保存图片', '收藏'],
	  							success: function(data) {
	  								uni.showToast({
	  									title:"功能测试中",
	  									icon:"none",
	  									duration:1000
	  								})
	  							},
	  							fail: function(err) {
	  								console.log(err.errMsg);
	  							}
	  						}
	    					});
	    				})
	    				.catch(error => {
	    					// 图片加载失败
	    					uni.hideLoading()
	    				})
	  },
	  changeFollow(){
			if(this.isFollow==false){
				method.followUser(this.myUid,this.uid,this.myUid,this.token,"个人主页").then((result) => {
					this.isFollow=true
					  uni.showToast({
					  	title:result.message,
						icon:"none",
						duration:500
					  })
				})
				.catch((error) => {
					uni.showToast({
						title:error.message,
						icon:"none",
						duration:2000
					})
				});
			}else{
				uni.showModal({
					title:"FBI WARNING！",
					content:"确定要取消关注吗？",
					cancelText:"算了",
					confirmText:"我要取关",
					success: (res) => {
						if(res.confirm){
						//向后端发送取消关注请求
						method.cancelFollowUser(this.myUid,this.uid,this.myUid,this.token).then((result) => {
							this.isFollow=false;
							  uni.showToast({
							  	title:result.message,
								icon:"none",
								duration:500
							  })
						})
						.catch((error) => {
							uni.showToast({
								title:error.message,
								icon:"none",
								duration:2000
							})
						});
						}else{
							return;
						}
					}
				})
			}
	  },
	  gotoPost(postId){
		  console.log("postId",postId)
	  	uni.navigateTo({
	  		url:'/pages/blogArticleDisplay/blogArticleDisplay?id='+postId
	  	});
	  },
	  getUserAvatar(){
		  
		  if(this.myUid==this.uid){
			  this.userAvatar=uni.getStorageSync('userAvatar'+this.myUid)
			  return
		  }
	  		  uni.request({
	  		      url: this.baseUrl+'/getUserAvatar',
	  		      method: 'POST',
	  		      data: {
	  		  		data:{
	  		  			userId:this.uid
	  		  		},
	  		  		msgType:'getUserAvatar'
	  		      },
	  		      header: {
	  		  		'Content-Type': 'application/json',
	  		  		'token':this.token,
	  		  		'uid':this.myUid
	  		      },
	  		      success: (res) => {
	  		  		console.log(res);
	  		  		if(res.data.code==1){
	  		  			const userAvatar=res.data.data.imgType+'base64,'+res.data.data.userAvatar;
	  		  			this.userAvatar=userAvatar;
						uni.setStorageSync('userAvatar'+this.uid,this.userAvatar)
	  		  		}else{
	  					// 该用户服务器没有设置头像,启用默认头像
	  					
	  				}
	  		      },
	  		      fail: (err) => {
	  		  		console.error('请求失败:', err);
	  		      }
	  		  });
	  },
    goToChat(uid, username) {
      uni.navigateTo({
        url: "/pages/chat/chat?uid=" + uid + "&username=" + username
      });
    },
  }
};
</script>

<style scoped>
.profile {
  padding: 0 30rpx;
  font-family: Arial, sans-serif;
  display: flex;
  flex-direction: column;
  height: 100vh;
}
.header {
  display: flex;
  align-items: center;
  padding: 30rpx;
  background-color: #ffffff;
  border-radius: 20rpx;
  box-shadow: 0 8rpx 16rpx rgba(0, 0, 0, 0.1);
}
.noTags{
	text-align: center;
	color: grey;
	margin: auto;
	font-size: 30rpx;
}
.avatar {
  width: 2000rpx;
  height: 200rpx;
  border-radius: 50%;
  border: 6rpx solid #dddddd;
}
.info {
  margin-left: 30rpx;
}
.nickname {
  font-size: 50rpx;
  font-weight: bold;
  color: #333333;
}
.follow-icon{
	display: inline-block;
	color: aqua;
	border-radius: 25rpx;
	font-size: 30rpx;
	margin-left: 30rpx;
}
.notFollow{
	color: #000;
}
.followed{
	color: #888;
}
.chat-icon {
  margin-left:30rpx; /* 添加左边距，确保与昵称之间有间隔 */
  color: #007acc; /* 设置颜色 */
  font-size: 28rpx; /* 设置字体大小 */
}
.follow-info {
  display: flex;
  flex-direction: column;
}
.follow {
  color: #888888;
  margin-top: 10rpx;
  font-size: 28rpx;
}
.achievements {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  margin-top: 30rpx;
  background-color: #ffffff;
  border-radius: 20rpx;
  box-shadow: 0 8rpx 16rpx rgba(0, 0, 0, 0.1);
}
.level-info {
  display: flex;
  flex-direction: column;
  margin-left: 40rpx;
}
.level {
  color: #666666;
  font-size: 28rpx;
  font-weight: bold;
}
.tags {
  display: flex;
  flex-wrap: wrap;
  padding: 30rpx 20rpx;
  margin-top: 30rpx;
  background-color: #ffffff;
  border-radius: 20rpx;
  box-shadow: 0 8rpx 16rpx rgba(0, 0, 0, 0.1);
}
.tag {
  background-color: #e6f3ff;
  color: #007acc;
  padding: 16rpx 30rpx;
  margin: 10rpx;
  border-radius: 30rpx;
  font-size: 28rpx;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
}
.blog-list {
  overflow-y: scroll;
  padding: 20rpx 0;
}
.blog-item {
  display: flex;
  justify-content: space-between;
  padding: 30rpx 30rpx;
  margin-bottom:20rpx ;
  background-color: #ffffff;
  border-radius: 20rpx;
  box-shadow: 0 8rpx 16rpx rgba(0, 0, 0, 0.1);
}
.blog-title {
  font-size: 35rpx;
  width: 450rpx;
  color: #333333;
  font-weight: bold;
}
.blog-date {
  font-size: 28rpx;
  color: #aaaaaa;
}
</style>
